package com.iwop.moto.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.model.*;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.alipay.AliPayUtil;
import com.iwop.moto.utils.stringUtil.AmountUtils;
import com.iwop.moto.utils.stringUtil.JsonUtils;
import com.iwop.moto.utils.stringUtil.StringUtils;
import com.iwop.moto.utils.weixin.WeixinUtil;
import com.iwop.moto.utils.weixin.utils.WxPayUtil;
import com.wordnik.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mobom on 2016/11/21.
 */
@Controller
public class MPayMentController extends BaseController {

    @Autowired
    private MPaymentService mPaymentService;

    @Autowired
    private MWithdrawService mWithdrawService;

    @Autowired
    UserService userService;

    @Autowired
    private MOrderPurchaseService mOrderPurchaseService;

    @Autowired
    private MGPOrderService mgpOrderService;

    @Autowired
    FOrderServiceService fOrderServiceService;

    @Autowired
    WxPayService wxPayService;
    /**
     * 今日收入
     * session_id用户id
     */
    @RequestMapping("/api/payment/list")
    @ResponseBody
    public ResultModel payMentList(HttpServletRequest request) {
        try {
            SuperRecordModel srModel = this.getSRModel();
            List<SuperRecordModel> list = mPaymentService.getPaymentDayByUserId(srModel);
            return getSucceed(list, ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能：收入明细
     *
     * @param rows       行数
     * @param pages      页码
     * @param session_id 用户id
     */
    @RequestMapping("/shop/payment/transaction/list")
    @ResponseBody
    public ResultModel getPayMentList(HttpServletRequest request) {
        try {
            SuperRecordModel srModel = new SuperRecordModel();
            String rows = request.getParameter("rows");
            String pages = request.getParameter("pages");
            String session_id = request.getParameter("session_id");
            String ctype = request.getParameter("ctype");
            if(StringUtils.isEmpty(ctype)){
                ctype="store";
            }
            if (StringUtils.isEmpty(rows)) {
                rows = "10";
            }
            if (StringUtils.isEmpty(pages)) {
                pages = "1";
            }
            int row = StringUtils.getSafeInt(rows);
            int page = StringUtils.getSafeInt(pages);
            int offset = (page - 1) * row;
            srModel.put("offset", offset);
            srModel.put("ctype", ctype);
            srModel.put("maxrow", row);
            srModel.put("user_id", session_id);
            List<SuperRecordModel> getPayMentList = mPaymentService.getPayMentList(srModel);
            Long count=mPaymentService.countPayMent(srModel);
            count= ((count - 1) / row) + 1;
            return getSucceed(getPayMentList, ErrCode.SUCCEED,count+"");
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能：收入明细
     *
     * @param rows       行数
     * @param pages      页码
     * @param session_id 用户id
     */
    @RequestMapping("/shop/payment/transaction/list_new")
    @ResponseBody
    public ResultModel getNewPayMentList(HttpServletRequest request) {
        try {
            SuperRecordModel srModel = new SuperRecordModel();
            String rows = request.getParameter("rows");
            String pages = request.getParameter("pages");
            String session_id = request.getParameter("session_id");
            String ctype = request.getParameter("ctype");
            if(StringUtils.isEmpty(ctype)){
                ctype="store";
            }
            if (StringUtils.isEmpty(rows)) {
                rows = "10";
            }
            if (StringUtils.isEmpty(pages)) {
                pages = "1";
            }
            int row = StringUtils.getSafeInt(rows);
            int page = StringUtils.getSafeInt(pages);
            int offset = (page - 1) * row;
            srModel.put("offset", offset);
            srModel.put("ctype", ctype);
            srModel.put("maxrow", row);
            srModel.put("user_id", session_id);
            List<SuperRecordModel> getPayMentList = mPaymentService.getNewPayMentList(srModel);
            Long count=mPaymentService.countPayMent(srModel);
            count= ((count - 1) / row) + 1;
            ResultModel resultModel=new ResultModel();
            resultModel.setData(JSON.toJSONString(getPayMentList));
            resultModel.setCode(1);
            resultModel.setAnnex(count+"");
            return resultModel;
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }



    /**
     * 功能：收入明细详情
     *
     * @param session_id 用户id
     * @param mid        M_WITHDRAW表主键
     * @param pid        m_payment表的主键
     */
    @RequestMapping("/shop/payment/transaction/list/detail")
    @ResponseBody
    public ResultModel getPayMentDetail(HttpServletRequest request) {
        try {
            String pid = request.getParameter("pid");
            String mid = request.getParameter("mid");
            ResultModel resultModel=new ResultModel();
            SuperRecordModel superRecordModel = null;
            if (!StringUtils.isEmpty(mid)) {
                superRecordModel = mWithdrawService.findWithDrawBySid(mid);
                resultModel.setData(JSON.toJSONString(superRecordModel));
                resultModel.setCode(1);
                return resultModel;
            } else {
                superRecordModel = mPaymentService.findPayMentByPayId(pid);
                resultModel.setData(JSON.toJSONString(superRecordModel));
                resultModel.setCode(1);
                return resultModel;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    /**
     * 订单交易记录
     * oid 订单id
     * */
    @RequestMapping(value = "/payment/detail", method = RequestMethod.GET)
    @ResponseBody
    public ResultModel payMentDetail(@ApiParam(name = "oid", value = "订单id", defaultValue = "")
                                         @RequestParam(value = "oid") String oid) throws Exception {
        try {
            MPayment payment = mPaymentService.findMPaymentByOrderId(oid);
            if("Topup".equals(payment.getPayType())){
                return getSucceed(payment,ErrCode.SUCCEED);
            }else if(payment.getOutTradeNo().contains("Co")) {
                MOrderPurchase mOrderPurchase = mOrderPurchaseService.findModerPurchaseByOid(payment.getOutTradeNo());
                mOrderPurchase.setCouponMoney(payment.getCouponMoney());
                mOrderPurchase.setBrokerage(payment.getBrokerage());
                mOrderPurchase.setMchType(payment.getMchType());
                List<FOrderPurchaseDetail> purchaseDetailByOid = mOrderPurchaseService.findPurchaseDetailByOid(mOrderPurchase.getSid());
                mOrderPurchase.setList(purchaseDetailByOid);
                return getSucceed(mOrderPurchase,ErrCode.SUCCEED);
            }else if(payment.getOutTradeNo().contains("Ho")){
                MGPOrder mgpOrder=mgpOrderService.findOneBySid(payment.getOutTradeNo());
                mgpOrder.setCouponMoney(payment.getCouponMoney());
                mgpOrder.setBrokerage(payment.getBrokerage());
                mgpOrder.setMchType(payment.getMchType());
                return getSucceed(mgpOrder,ErrCode.SUCCEED);
            }else {
                SuperRecordModel superRecordModel = fOrderServiceService.findStoreOrderByOrderId(payment.getOutTradeNo());
                superRecordModel.put("couponMoney",payment.getCouponMoney());
                superRecordModel.put("brokerage",payment.getBrokerage());
                superRecordModel.put("mchType",payment.getMchType());
                List<SuperRecordModel> list = fOrderServiceService.getStoreOrderDetail(superRecordModel.getString("sid"));
                superRecordModel.put("list",list);
                return getSucceed(superRecordModel,ErrCode.SUCCEED);
            }
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }

    }

    @RequestMapping("/payment/update/data")
    @ResponseBody
    public ResultModel findPaymentAll(Date startTime) throws Exception {
       mPaymentService.updateMpayData(startTime);
        return getSucceed(ErrCode.SUCCEED);
    }

    @RequestMapping("/payment/update/data/payno")
    @ResponseBody
    public ResultModel findPaymentPayNo() throws Exception {
        List<MPayment> list=mPaymentService.findAllData();
        for (MPayment mPayment:list){
            SuperRecordModel superRecordModel=wxPayService.findByOutTradeNo(mPayment.getOutTradeNo());
            if(null!=superRecordModel){
                mPayment.setPayTradeNo(superRecordModel.getString("transaction_id"));
                mPaymentService.updateMPayMent(mPayment);
            }
        }
        return getSucceed(ErrCode.SUCCEED);
    }
}
